import axios from 'axios';
import {
    Message,
    Loading
} from 'element-ui';
import router from '../router/index';
axios.defaults.timeout = 5000; //超市时间是5秒
axios.defaults.withCredentials = true; //允许跨域
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = "http://localhost:8001";


// Loading的option
const options = {
    text: '拼命加载中...',
    background: 'rgba(255,255,255,0.6)',
    spinner: 'el-icon-loading',
    lock: true,
    target: '.loading' // target指定需要覆盖的 DOM 节点，会获取到问的那个中第一个类名为right-container的元素
}
let loadingInstance;



//前置拦截
axios.interceptors.request.use(config => {
    if (loadingInstance) {
        loadingInstance.close(); //因为option设置了target, 指定target时，每次都创建了一个新的实例,故需在拦截器调用新的Loading之前检测是否有实例存在，若存在，应将其关闭。
    }
    loadingInstance = Loading.service(options); // 以服务的方式调用的 Loading
    return config;
});

//后置拦截
axios.interceptors.response.use(response => {
        let res = response.data;
        if (loadingInstance) {
            loadingInstance.close(); //关闭Loading
        }
        if (res.code == 200) {
            return response.data.data;
        } else if (res.code == 401) {
            Message.warning(res.msg);
            router.push("/");
            return Promise.reject("");
        } else {
            Message.warning(res.msg);
            return Promise.reject("");
        }
    },
    error => {
        // store.commit("REMOVE_INFO");
    }
);


/**
 * 封装get方法
 */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params
            })
            .then(response => {
                resolve(response);
            })
            .catch(err => {
                reject(err);
            })
    });
}

/**
 * 封装post方法
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response);
            })
            .catch(err => {
                reject(err);
            })
    });
}
